package cn.edu.swu.gyt.controller;

import cn.edu.swu.gyt.repo.BookResultSetVisitor;
import cn.edu.swu.gyt.repo.DatabaseService;
import cn.edu.swu.gyt.utils.HTMLHelper;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.List;


@WebServlet(urlPatterns = "/admin/books")
public class BookServlet extends HttpServlet {
       public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException {
           ServletContext context =request.getServletContext();
           DatabaseService service =(DatabaseService) context.getAttribute(DatabaseService.CONTEXT_KEY);
           try {
               List<Book> books=service.query("select * from books order by id desc",new BookResultSetVisitor());
               response.setContentType("text/html");
               response.setCharacterEncoding("UTF-8");
               try(Writer writer=response.getWriter()){
                   String table=HTMLHelper.buildBooksTable(books);
                   String html= HTMLHelper.wrapHtml(table);
                   writer.write(html);
                   writer.flush();
               }
           } catch (SQLException | IOException e) {
               throw new ServletException(e);
           }
       }



}
